<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <div class="formTitle-root">
      <div class="form-title-p">下发计划信息</div>
    </div>
    <VForm
      ref="vformComponents1"
      :form="formData1.form"
      :options="formData1.options"
      :rules="formData1.rules"
      :labelWidth="formData1.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <div class="formTitle-root">
      <div class="form-title-p">分派信息</div>
    </div>
    <div>
      <el-table :data="planAssignItemList" border>
        <el-table-column
          prop="sort"
          label="序号"
          width="50"
        ></el-table-column>
        <el-table-column prop="patrolObjectName" label="*巡查对象">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.patrolObjectName"
              allow-create
              filterable
              default-first-option
              placeholder="巡查对象"
              @change="patrolObjectNameChange(scope.row)"
              v-if = "openType!='detail'"
            >
              <el-option
                v-for="item in patrolObjectList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
            <div v-else>
              <el-input type="text" v-model="scope.row.patrolObjectName" disabled = true></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="patrolAddress" label="*巡查对象地址">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.patrolAddress"
              placeholder="巡查对象地址"
              :disabled = "openType=='detail'"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="patrolPersonId" label="*巡查人员">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.patrolPersonId"
              filterable
              default-first-option
              placeholder="巡查人员"
              @change="patrolPersonIdChange(scope.row)"
              v-if="openType!='detail'"
            >
              <el-option
                v-for="item in patrolPersonList"
                :key="item.userId"
                :label="item.nickname"
                :value="item.userId"
              >
              </el-option>
            </el-select>
            <div v-else>
              <el-input type="text" v-model="scope.row.patrolPerson" disabled = true></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100"
          v-if="openType!='detail'"
        >
          <template slot-scope="scope">
            <span
              @click="deleteItem(scope)"
              style="cursor: pointer; color: red"
            >删除</span
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top:20px; float: right"  v-if="openType!='detail'">
      <el-button
        icon="el-icon-circle-plus-outline"
        type="primary"
        plain
        style="float: left;"
        size="small"
        @click="addPatrolAssignItem"
      >添加巡查对象</el-button>
    </div>

      <span slot="footer" class="dialog-footer">
     <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
     <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    patrolPatrolPlanAssignDetail,
    patrolPatrolPlanAssignUpdate,
    patrolModelList
  } from '@/api/risk/patrol'
  import {
    getInstPersonList
  } from '@/api/system/institution'
  import {
    getDeptList,getUserList
  } from '@/api/risk/dept'
  import {
    alarmFacilityList
  } from '@/api/alarm/facility.js'
  import { treeDataChild } from '@/api/risk/treeData'
  import VForm from "@/components/VForm/index";
  import { collectBuildingProjectList } from '@/api/build/project'
  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "80%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      bClassifyOptions:{},
      planTypeOptions:{}
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiLargeType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'planTypeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='planType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'planCycleOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='planCycle'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptionsForm':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiSmallType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'modelList':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='modelId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiLargeType':{
        handler(newVal, oldVal) {
          this.watchChangeLargeType()
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiSmallType':{
        handler(newVal, oldVal) {
          this.watchChangeSmallType()
        },
        deep: true,
        immediate: true
      },
      'belongUnitIdList':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='execUnitId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'openType':{
        handler(newVal, oldVal) {
          // 判断是否详情，添加不可编辑标识
          this.formData.options.forEach(t=>{
            t.disabled = true
          })
          this.formData1.options.forEach(t=>{
            t.disabled = true
          })
        },
        deep: true,
        immediate: true
      },
      'buildingOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'buildingId') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        planAssignItemList:[],
        rowspan:1,
        dict:{},
        formData: {
          form: {
            id:"",
            planName:"",
            busiLargeType:"",
            busiSmallType:"",
            modelId:"",
            planType:"",
            planCycle:"",
            execUnitId:"",
            execUnit:"",
            planStartDate:"",
            planEndDate:"",
            remark:"",
            buildingId: "",
          },
          options: [
            {
              title: "所属工地",
              key: "buildingId",
              type: "select",
              multiple: false,
              option: {
                data: this.buildingOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "projectName", // 指定label对应data的字段
                  value: "id", //指定value对应data的字段
                }
              }
            },
            {
              title: "计划名称",
              key: "planName",
              type: "text",
            },
            {
              title: "业务专题大类",
              key: "busiLargeType",
              type: "select",
              multiple:false,
              event: 'changeLargeType',
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title: "业务专题细类",
              key: "busiSmallType",
              type: "select",
              multiple:false,
              event: 'changeSmallType',
              option: {
                data: this.sClassifyOptionsForm,
                props: {
                  key: "code", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "code", // 指定value对应data的字段
                },
              },
            },
            {
              title: "巡查表单",
              key: "modelId",
              type: "select",
              multiple:false,
              option: {
                data: this.modelList,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "modelName", // 指定label对应data的字段
                  value: "id", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划巡检类型",
              key: "planType",
              type: "select",
              multiple:false,
              option: {
                data: this.planTypeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划周期",
              key: "planCycle",
              type: "select",
              multiple:false,
              option: {
                data: this.planCycleOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "执行单位",
              key: "execUnit",
              type: "text",
            },
            {
              title: "计划开始日期",
              key: "planStartDate",
              type: "date",
            },
            {
              title: "计划结束日期",
              key: "planEndDate",
              type: "date",
            },
            {
              title: "计划描述",
              key: "remark",
              type: "textarea",
              columnWidth: 'w100max',
            },
          ],
          rules: {},
          labelWidth: "140px",
        },
        formData1:{
          form: {
            execStreetUnitId:"",
            execStreetUnit:"",
            execRequire:""
          },
          options:[
            {
              title: "执行单位",
              key: "execStreetUnit",
              type: "text",
            },
            {
              title: "执行要求",
              key: "execRequire",
              type: "textarea",
              columnWidth: 'w100max',
            },
          ],
          rules: {},
          labelWidth: "140px",
        },
        // 字典
        sClassifyOptionsForm:[],
        modelList:[],
        planCycleOptions:[],
        patrolTaskObjectAssociationOptions:[],
        patrolObjectList:[],
        patrolPersonList:[],
        buildingOptions: [],
      };
    },
    methods: {
      deleteItem(scope) {
        console.log(scope);
        let list = this.planAssignItemList;
        let filterList = list.filter((t) => {
          return t.sort != scope.row.sort;
        });
        let index = 1;
        filterList.forEach((t) => {
          (t.sort = index), index++;
        });
        this.planAssignItemList = filterList;
      },
      addPatrolAssignItem(){
        let item = {
          patrolObjectId:"",
          patrolObjectName:"",
          patrolAddress:"",
          patrolPersonId:"",
          patrolPerson:"",
          sort: this.planAssignItemList.length + 1,
        }
          this.planAssignItemList.push(item)
      },
      patrolObjectNameChange(row){
          // 获取id
          let item = this.patrolObjectList.find(t=>t.name == row.patrolObjectName)
          // 不为空设置id和地址
          if(undefined!=item){
             this.$set(this.planAssignItemList[row.sort-1], "patrolObjectId", item.id)
             this.$set(this.planAssignItemList[row.sort-1], "patrolAddress", item.address)
             return
          }
          this.$set(this.planAssignItemList[row.sort-1], "patrolObjectId", '')
          this.$set(this.planAssignItemList[row.sort-1], "patrolAddress", '')
      },
      patrolPersonIdChange(row){
        console.log("............111",this.patrolPersonList,row.patrolPersonId);
        let item = this.patrolPersonList.find(t=>t.userId == row.patrolPersonId)
        console.log("item>>>",item);
        if(undefined!=item){
          this.$set(this.planAssignItemList[row.sort-1], "patrolPerson", item.nickname)
        }
      },
      noBlank(val) {
        if (val != "" && val != null && val != undefined) {
          return true;
        }
        return false;
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      watchChangeSmallType(){
        // 防止详情查询不出
         let data = {
           busiLargeType:this.formData.form.busiLargeType,
           busiSmallType:this.formData.form.busiSmallType,
           delFlag:0,
           disableFlag:0
         }
         patrolModelList(data).then(res=>{
           if(res.code==200){
             this.modelList = res.data
           }
         })
      },
      watchChangeLargeType(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.formData.form.busiLargeType
        treeDataChild(queryData).then(res=>{
          if(res.code==200) {
            this.sClassifyOptionsForm = res.data
          }
        })
      },
      changeLargeType(){
        this.formData.form.busiSmallType = ''
      },
      changeSmallType(){
          this.formData.form.modelId = ''
      },
      initData(){
          this.formData.form.id = "",
          this.formData.form.planName = "",
          this.formData.form.busiLargeType = "",
          this.formData.form.busiSmallType = "",
          this.formData.form.modelId = "",
          this.formData.form.planType = "",
          this.formData.form.planCycle = "",
          this.formData.form.execUnitId = "",
          this.formData.form.execUnit = "",
          this.formData.form.planStartDate = "",
          this.formData.form.planEndDate = "",
          this.formData.form.remark = ""
          this.formData1.form.execStreetUnit = ""
          this.formData1.form.execStreetUnitId = ""
          this.formData1.form.execRequire = ""
          this.modelList= []
          this.sClassifyOptionsForm = []
          this.planAssignItemList = []
          this.patrolObjectList = []
          this.patrolPersonList = []
      },
      sure(){
        console.log('sure===',this.formData.form)
            if(!this.planAssignItemListValid()){
              this.$message.warning("请完善分派信息！")
              return
            }
            let tempParams = {
              id:this.formData.form.id,
              planAssignItemList:this.planAssignItemList
            }
          if(this.openType == "add"){
            this.add()
          }else{
            this.update(tempParams)
          }
      },
      planAssignItemListValid(){
         if(this.planAssignItemList.length==0){
           return false
         }
         let flag = true
          console.log(">>>>>>>>>>>...",this.planAssignItemList);
         this.planAssignItemList.forEach(t=>{
            if(!this.noBlank(t.patrolObjectName) || !this.noBlank(t.patrolAddress)
              || !this.noBlank(t.patrolPersonId) || !this.noBlank(t.patrolPerson)){
              flag = false;
            }
         })
         return flag;
      },
      add(){
        // this.formData.form.id = null
        // patrolPlanDistributeAdd(this.formData.form).then(res=>{
        //   if(res.code==200){
        //     this.$message({
        //       message: this.$t('tips.createSuccess'),
        //       type: 'success'
        //     })
        //     this.closeSuccess()
        //   }else{
        //     this.$message({
        //       message: res.message,
        //       type: 'error'
        //     })
        //   }
        // })
      },
      update(tempParams){
        patrolPatrolPlanAssignUpdate(tempParams).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('success')
      },
      close(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('close')
      },
      /**
       * 获取对应类型设施
       * @param smallType
       */
      getPatrolObjectList(smallType){
        console.log("getPatrolObjectList(", smallType)
        let modeType = null
        this.patrolObjectList = []
        for(let key in this.patrolTaskObjectAssociationOptions){
          let item = this.patrolTaskObjectAssociationOptions[key]
          let o = JSON.parse(item.label)
          if(o.code==smallType){
             modeType = item.name
          }
        }
        if(modeType!=null){
          let areaCode = this.$store.state.account.user.deptIds
          // 截取6位，areaCode可能只到区
          if(this.$store.state.account.user.deptIds.length>6){
            areaCode = this.$store.state.account.user.deptIds.substring(0,6)
          }
          let params = {
            // areaCodeFormat:areaCode,
            modeType:modeType
          }
          alarmFacilityList(params).then(res=>{
            if(res.code==200){
              this.patrolObjectList = res.data.map(t=>{ return { id:t.id, name:t.name, address:t.address}})
            }
          })
        }
          // this.patrolObjectList = [{id:"11",name:"丝源大厦",address:"广东省广州市天河区科华街1号"},
          //   {id:"22",name:"201室",address:"广东省广州市天河区科华街1号201室"}]
      },
      getPatrolPersonList(deptId){



        getUserList({deptId: deptId}).then(res=>{
            if(res.code ==200){
              this.patrolPersonList = res.data
              console.log(">############",this.patrolPersonList)
            }
        })

      },

      getBuildingList() {
        collectBuildingProjectList().then(res => {
          if (res.code == 200) {
            this.buildingOptions = res.data
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },

      getData(){
        this.planCycleOptions = []
        this.$commonJs.filterDataDict("patrolPlanCycle",this.planCycleOptions)
        this.patrolTaskObjectAssociationOptions = []
        this.$commonJs.filterDataDict("patrolTaskObjectAssociation",this.patrolTaskObjectAssociationOptions)
        this.getBuildingList();
        if(this.openType!="add"){
          patrolPatrolPlanAssignDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data
              this.formData1.form.execStreetUnit = res.data.execStreetUnit
              this.formData1.form.execStreetUnitId = res.data.execStreetUnitId
              this.formData1.form.execRequire = res.data.execRequire
              this.planAssignItemList = res.data.planAssignItemList
              this.getPatrolObjectList(res.data.busiSmallType)
              // 获取对应执行街道id人员信息
              this.getPatrolPersonList(res.data.execStreetUnitId)
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 10px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
  /*修改禁用样式*/
  ::v-deep .is-disabled .el-input__inner  {
    background-color:white;
    color: rgb(0, 0, 0);
  }
  ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner{
    border-color: $--color-primary;
    background: $--color-primary;
  }
  ::v-deep .el-radio__input.is-disabled + span.el-radio__label{
    color: rgb(0, 0, 0);
  }
  ::v-deep .el-textarea.is-disabled .el-textarea__inner{
    background: white;
    color: rgb(0, 0, 0);
  }
</style>
